package com.bootdo.common.controller;

import com.bootdo.common.utils.R;
import com.bootdo.common.utils.RedisUtils;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.system.domain.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class BaseController {

	@Autowired
	public CacheManager cacheManager;

	@Autowired
	public RedisUtils redisUtils;

	public UserDO getUser() {
		return ShiroUtils.getUser();
	}

	public Long getUserId() {
		return getUser().getUserId();
	}

	public String getUsername() {
		return getUser().getUsername();
	}

	public void setDateQuery(Map<String, Object> params) {
		String createdTimeStart = (String) params.get("createdTimeStart");
		String createdTimeEnd = (String) params.get("createdTimeEnd");
		if (StringUtils.isNotEmpty(createdTimeStart)) {
			params.put("createdTimeStart", createdTimeStart + " 00:00:00");
		}
		if (StringUtils.isNotEmpty(createdTimeEnd)) {
			params.put("createdTimeEnd", createdTimeEnd + " 23:59:59");
		}
	}

	public R checkToken(HttpServletRequest request) {
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)) {
			return R.error(300,"当前用户信息已失效，请重新登录");
		}
		UserDO userDO = (UserDO) redisUtils.get(token);
		if(null == userDO) {
			return R.error(300,"当前用户信息已失效，请重新登录");
		}
		return R.ok(userDO);
	}
}